package com.ys.config;

import java.util.Arrays;
import java.util.List;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Component
public class GlobalCorsConfig {
	
	@Bean
    public static FilterRegistrationBean<CorsFilter> configurationSource() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        
		corsConfig.addAllowedOrigin(CorsConfiguration.ALL);
		corsConfig.addAllowedMethod(CorsConfiguration.ALL);
		corsConfig.addAllowedHeader(CorsConfiguration.ALL);
		//默认可不设置这个暴露的头。这个为了安全问题，不能使用*。设置成*，后面会报错：throw new IllegalArgumentException("'*' is not a valid exposed header value");
		//corsConfig.addExposedHeader("");
		corsConfig.setMaxAge(3600L);
		
		UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
		configSource.registerCorsConfiguration("/**", corsConfig);
		
		FilterRegistrationBean<CorsFilter> corsBean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(configSource));
		corsBean.setName("crossOriginFilter");
		corsBean.setOrder(0);//这个顺序也有可能会有影响，尽量设置在拦截器前面
		return corsBean;
		
//        List<String> allowedHeaders = Arrays.asList("x-auth-token", "content-type", "X-Requested-With", "XMLHttpRequest");
//        List<String> exposedHeaders = Arrays.asList("x-auth-token", "content-type", "X-Requested-With", "XMLHttpRequest");
//        List<String> allowedMethods = Arrays.asList("POST", "GET", "DELETE", "PUT", "OPTIONS");
//        List<String> allowedOrigins = Arrays.asList("*");
//        corsConfig.setAllowedHeaders(allowedHeaders);
//        corsConfig.setAllowedMethods(allowedMethods);
//        corsConfig.setAllowedOrigins(allowedOrigins);
//        corsConfig.setExposedHeaders(exposedHeaders);
//        corsConfig.setMaxAge(36000L);
//        corsConfig.setAllowCredentials(true);
//
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/**", corsConfig);
//       return source;
    }    
}
